package com.s2paganini.display 
{
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.text.TextField;		

	/**
	 * @author siLvio paganini | s2paganini.com
	 * @purpose Custom Loader
	 */

	public class CustomLoader extends Loader 
	{
		private var $progressBar : Sprite;
		private var $fieldPerc : TextField;
		private var $progressBarProp : String;
		
		public function CustomLoader()
		{
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, listenerError);
			contentLoaderInfo.addEventListener(IOErrorEvent.NETWORK_ERROR, listenerError);
			contentLoaderInfo.addEventListener(Event.OPEN, listenerEvents);
		}
		
		/**
		 * Set default progress bar
		 * @param progressBar Array with 2 values [progressBar : Sprite, whichPropToChange : String]
		 * @param fieldPerc TextField to put loading percentage
		 */
		public function setLoadBar(progressBar : Array, fieldPerc : TextField = null) : void
		{
			if(progressBar.length > 0) $progressBar = progressBar[0];
			if(progressBar.length > 1) $progressBarProp = progressBar[1];
			$fieldPerc = fieldPerc;
			contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, listenerProgress);
		}
		
		/**
		 * Return the BitmapData of the Loader
		 */
		public function getBitmapData(smooth : Boolean = true, matrix : Matrix = null, colorTransform : ColorTransform = null, blendMode : String = null, clipRect : Rectangle = null) : BitmapData
		{
			var bmpData : BitmapData = new BitmapData(width, height);
			bmpData.draw(this, matrix, colorTransform, blendMode, clipRect, smooth);
			return bmpData; 
		}
		
		/**
		 * Return the Bitmap of the Loader
		 */
		public function getBitmap() : Bitmap
		{
			var bmpData : BitmapData = new BitmapData(width, height);
			bmpData.draw(this, null, null, null, null, true);
			
			var bitmap : Bitmap = new Bitmap(bmpData, "auto", true);
			return bitmap; 
		}

		private function listenerEvents(event : Event) : void
		{
			switch(event.type) {
				case "open":
					if($progressBar) $progressBar[$progressBarProp] = 0;
					break;	
			}
		}

		private function listenerProgress(event : ProgressEvent) : void
		{
			var perc : Number = event.bytesLoaded / event.bytesTotal;
			if($progressBar) $progressBar[$progressBarProp] = perc;
			if($fieldPerc) $fieldPerc.text = Math.round(perc * 100) + "%";
		}

		private function listenerError(event : IOErrorEvent) : void
		{
			trace(event.text);
		}
	}
}
